<?php

include 'CSSmin.php';
include 'JSmin.php';
include 'JSpacker.php';

class Layout extends Varien_Object {

    protected static $files = array();
    protected static $noPackJS = array();
    var $load;
    var $loadedData = array();
    private $ci;

    public function Layout($layout = "layouts/main/main") {
        $this->AddCssJs();
        $this->loadedData['_this'] = &$this;
        $obj = & get_instance();
        $this->ci = $obj;
        $this->load = $obj->load;
        $this->setLayout($layout);
        $this->setHead('layouts/header/head');
        $this->setHeader('layouts/header/header');
        $this->setFooter('layouts/footer/footer');
        $this->setContent('layouts/main/content');
        $this->setMenu('layouts/main/menu');
        $this->setTitle('Dashboard');
    }

    function assign($data, $value = null) {

        if (is_array($data)) {
            unset($data['this']);
            unset($data['_this']);
            foreach ($data as $key => $value) {
                if ($key) {
                    $this->loadedData[$key] = $value;
                }
            }
        } elseif (is_string($data) && !in_array($data, array('this', '_this'))) {
            $this->loadedData[$data] = $value;
        }
        $this->loadedData['_this'] = &$this;
    }
    
    public function loadMenu()
    {
        global $current_user;
        $this->ci->load->library('cron');
        $this->ci->load->library('menu');
        $this->ci->load->library('Blockcache');
        $this->ci->load->model('campaign/campaign_model');
        if ($this->ci->session->userdata('customerId')) {
            $customerId = $this->ci->session->userdata('customerId');
        } else {
            $clientEmail = get_user_meta($current_user->data->ID, 'googleaccount');
            $customerId = $this->ci->cron->get_customer_by_email($clientEmail[0]);
            $customerId = ($customerId) ? $customerId : '';
            $this->ci->session->set_userdata('clientEmail', $clientEmail);
            $this->ci->session->set_userdata('customerId', $customerId);
        }
        if ($allCampaign = $this->ci->blockcache->get('allCampaign_' + $customerId)) {
            
        } else {
            if (user_can($current_user->data->ID, 'edit_report'))
                $allCampaign = $this->ci->campaign_model->getCampaignByCustomerId($customerId);
            else
                $allCampaign = $this->ci->campaign_model->getCampaignByCustomerId($customerId, 1);
            if($allCampaign) {
                foreach ($allCampaign as $k => $v) {
                    $tmpActive = $this->ci->campaign_model->getInfoActive($v['campaign_id'],'campaigns', 'campaign_id');
                    $allCampaign[$k]['active'] = $tmpActive[0];
                    if (user_can($current_user->data->ID, 'edit_report'))
                        $allCampaign[$k]['groups'] = $this->ci->campaign_model->getGroupByCampaignId($v['campaign_id']);
                    else 
                        $allCampaign[$k]['groups'] = $this->ci->campaign_model->getGroupByCampaignId($v['campaign_id'], 1);
                    if($allCampaign[$k]['groups']) {
                        foreach ($allCampaign[$k]['groups'] as $_k=>$_v) {
                            $tmpActive = $this->ci->campaign_model->getInfoActive($_v['adgroup_id'],'adgroup', 'adgroup_id');
                            $allCampaign[$k]['groups'][$_k]['active'] = $tmpActive[0];
                        }
                    }
                }
            }
            $this->ci->blockcache->save('allCampaign_' + $customerId, $allCampaign, 5000);
        }
        if($allCampaign) {
            $index = 1;
            foreach ($allCampaign as $k=>$v) {
                $this->ci->menu->addMenu($v['campaign_id'],$v['name'], 'home/adgroup/'.$v['campaign_id'] ,$index,0);
                if($v['active']['active'] == 'PAUSED' || $v['active']['active'] == 'DELETED')
                    $this->ci->menu->setVisible($v['campaign_id'], false);
                else
                    $this->ci->menu->setVisible($v['campaign_id']);
                if($v['groups']) {
                    $_index = 1;
                    foreach ($v['groups'] as $_k=>$_v) {
                        $this->ci->menu->addSubmenu($v['campaign_id'], $_v['adgroup_id'], $_v['name'], 'home/ads/' . $v['campaign_id'] . '/' . $_v['adgroup_id'] , $index);
                        if ($_v['active']['active'] == 'DISABLED')
                            $this->ci->menu->setVisible($_v['adgroup_id'], false);
                        else
                            $this->ci->menu->setVisible($_v['adgroup_id']);
                        $_index++;
                    }
                }
                $index++;
            }   
        }
        $this->assign('menus', $this->ci->menu->renderMenu());
    }

    function reset() {
        $this->loadedData = array();
        $this->loadedData['_this'] = &$this;
    }

    function maybe_disabled($input = '') {
        $disabled = ' disabled="disabled"';
        if ($this->getReadOnly()) {
            echo $disabled;
            return true;
        } elseif ($input) {
            if ($this->getData('read_only_' . $input)) {
                echo $disabled;
                return true;
            }
        }
        return false;
    }

    function maybe_disabled_capability($capability) {
        $disabled = ' disabled="disabled"';
        if ($this->maybe_disabled())
            return;
        if (!current_user_can($capability))
            echo $disabled;
    }

    function view($view = null, $data = null, $return = false) {
        if ($data && is_array($data)) {
            $this->reset();
            $this->assign($data);
        }
        if ($view) {
            $this->setContent($view);
        }
        if ($return) {
            $output = $this->load->view($this->getLayout(), $this->loadedData, true);
            return $output;
        } else {
            if(is_user_logged_in())
                $this->loadMenu();
            $this->load->view($this->getLayout(), $this->loadedData, false);
        }
    }

    function viewChild($file, $data = array()) {
        if ($this->getData($file))
            $this->load->view($this->getData($file), $data);
    }

    protected function AddCssJs() {
        $this->AddCss('reset');
        $this->AddCss('base');
        $this->AddCss('style');
        $this->AddCss('jquery.jscrollpane');
        $this->AddSharedJs('jquery-1.6.4.min');
        $this->AddSharedJs('custom');
        $this->AddSharedJs('jquery.jscrollpane');
    }

    public function AddJsFileNoPack($files, $ext) {
        if (!$files)
            return;
        $ext = strtolower($ext);
        if ($ext == 'shared_js')
            $ext = 'js';
        $files = explode(',', $files);
        foreach ($files as $file) {
            $file = trim($file) . '.js';
            $path = DIR_JS . $file;
            self::$noPackJS[$path] = $file;
        }
    }

    public static function AddFile($files, $type) {
        if (!$files)
            return;
        $files = explode(',', $files);
        $ext = strtolower($type);
        if ($ext == 'shared_js')
            $ext = 'js';
        foreach ($files as $file) {
            $file = trim($file) . ".$ext";
            if ($ext == 'js') {
                $path = DIR_JS . $file;
            } else {
                $path = DIR_CSS . $file;
            }
            self::$files[$ext][$path] = $path;
        }
    }

    public function GetCombined($ext) {
        if (JS_COMBINE_MODE) {
            $src = $this->CombineFile($ext);
            $ext = strtolower($ext);
            $return_method = "Return$ext";
            $out[] = $this->$return_method($src);
        } else if (isset(self::$files[$ext])) {
            foreach (self::$files[$ext] as $file) {
                $src = $this->RenderFile($file);
                $return_name = "Return$ext";
                $out[] = $this->$return_name($src);
            }
        }
        if ($ext == 'js') {
            foreach (self::$noPackJS as $file) {
                $out[] = self::ReturnJsNoPack($file);
            }
        }
        return implode("\n", $out);
    }

    public static function Returncss($src) {
        return "<link rel='stylesheet' type='text/css' href='" . STATIC_DOMAIN . DIR_CACHE . "$src' />";
    }

    public static function Returnjs($src) {
        return "<script type='text/javascript' src='" . STATIC_DOMAIN . DIR_CACHE . "$src'></script>";
    }

    public static function ReturnJsNoPack($src) {
        return "<script type='text/javascript' src='" . STATIC_DOMAIN . DIR_JS . $src . "'></script>";
    }

    protected function CombineFile($ext) {
        $hash = $this->GetHash(self::$files[$ext]);
        $name = "$hash.$ext";
        $path = DIR_CACHE;
        $file = $path . $name;
        if (!file_exists($file)) {
            $this->MakeDir($path);
            $value = $this->Combine($file, self::$files[$ext]);
            $pack_method = "Pack$ext";
            $value = $this->$pack_method($value);
            $this->Write($ext . '_' . $file, $value);
        }
        return $name;
    }

    protected function GetHash($files) {
        $time = null;
        foreach ($files as $file) {
            if (file_exists($file))
                $time .= filemtime($file);
        }
        return substr(md5($time), 0, 16);
    }

    protected function RenderFile($origin_file) {
        if (!file_exists($origin_file))
            return null;
        $file_name = basename($origin_file);
        $base_path = dirname($origin_file);
        $ext = $this->GetExt($origin_file);
        $hash = filemtime($origin_file);
        $name = $this->GetName($origin_file) . ".$hash.$ext";
        $path = DIR_CACHE;
        $file = $path . '/' . $name;
        if (!file_exists($file)) {
            $pack_method = "Pack$ext";
            $value = $this->Read($origin_file);
            $value = $this->$pack_method($value);
            $this->MakeDir($path);
            $this->Write($file, $value);
        }
        return $name;
    }

    public function AddSharedJsNoPack($files) {
        $this->AddJsFileNoPack($files, 'SHARED_JS');
    }

    public function AddJsNoPack($files) {
        $this->AddJsFileNoPack($files, 'JS');
    }

    public function AddSharedJs($files) {
        $this->AddFile($files, 'SHARED_JS');
    }

    public function AddJs($files) {
        $this->AddFile($files, 'JS');
    }

    public function AddCss($files) {
        $this->AddFile($files, 'CSS');
    }

    public static function GetExt($file) {
        return strtolower(pathinfo($file, PATHINFO_EXTENSION));
    }

    public static function GetName($file) {
        return pathinfo($file, PATHINFO_FILENAME);
    }

    public static function MakeDir($dir, $chmod = 0777) {
        if (!file_exists($dir)) {
            mkdir($dir);
            chmod($dir, $chmod);
        }
    }

    public static function Write($file, $data, $mode = 'w') {
        $handle = fopen($file, $mode);
        fwrite($handle, $data);
        fclose($handle);
        return true;
    }

    public static function Read($file) {
        if (!file_exists($file))
            throw new Exception("File not found: $file");
        return file_get_contents($file);
    }

    public function Combine($combined_file, $files) {
        $combined = null;
        foreach ($files as $file) {
            if (file_exists($file)) {
                $tmptxt = $this->Read($file);
                $combined .= "\n" . $tmptxt;
            }
        }
        $this->Write($combined_file, $combined);
        return $combined;
    }

    public static function Packjs($js) {
        if (JS_PACK_MODE) {
            $packer = new JSpacker($js);
            return $packer->pack();
        } else if (JS_MINIFY_MODE)
            return JSmin::minify($js);
        else
            return $js;
    }

    public static function Packcss($css) {
        if (JS_PACK_MODE || JS_MINIFY_MODE) {
            $min = new CSSmin();
            return $min->minify($css);
        }
        else
            return $css;
    }

}

?>
